import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();
const SCORE_MAP = {
  'HT1': 60, 'LT1': 45, 'HT2': 30, 'LT2': 20,
  'HT3': 10, 'LT3': 6, 'HT4': 4, 'LT4': 3,
  'HT5': 2, 'LT5': 1
};

// 根据数值获取段位名称
function getTierName(tierValue: number | null): string {
  if (tierValue === null) return '无等级';
  
  const TIER_NAMES: Record<number, string> = {
    1: 'HT1',
    2: 'LT1',
    3: 'HT2',
    4: 'LT2',
    5: 'HT3',
    6: 'LT3',
    7: 'HT4',
    8: 'LT4',
    9: 'HT5',
    10: 'LT5'
  };
  
  return TIER_NAMES[tierValue] || '无等级';
}

// 计算玩家等级称号
function calculatePlayerLevel(totalScore: number): string {
  if (totalScore >= 250) return '战神';
  if (totalScore >= 100) return '战王';
  if (totalScore >= 50) return '战斗精英';
  if (totalScore >= 20) return '战斗学员';
  if (totalScore >= 10) return '战斗新手';
  return '菜鸟';
}

// 计算玩家段位总分
function calculateTierScore(player: any): number {
  let totalTierScore = 0;
  const modes = ['SWORD', 'CRYSTAL', 'BUHC', 'POTION', 'NPOT', 'SMP'];
  
  modes.forEach(mode => {
    const tierMap: Record<string, keyof typeof player> = {
      'SWORD': 'swordTier',
      'CRYSTAL': 'crystalTier',
      'BUHC': 'buhcTier',
      'POTION': 'potionTier',
      'NPOT': 'npotTier',
      'SMP': 'smpTier'
    };
    
    const tierKey = tierMap[mode];
    const tierValue = tierKey ? player[tierKey] : null;
    
    if (tierValue !== null) {
      // 获取段位名称
      const tierName = getTierName(tierValue);
      // 根据段位名称查找分数
      const tierScore = SCORE_MAP[tierName as keyof typeof SCORE_MAP] || 0;
      // 累加到总分
      totalTierScore += tierScore;
    }
  });
  
  return totalTierScore;
}

export async function GET() {
  try {
    const players = await prisma.player.findMany({
      include: { scores: true },
      orderBy: { createdAt: 'desc' }
    });

    const formattedPlayers = players.map(player => {
      // 解析地区信息
      let player_region = player.region;
      let player_region_id = null;
      let player_region_color = null;
      let player_is_blacklisted = false;
      
      // 检查是否为黑名单
      if (player_region && player_region.includes('[blacklisted]')) {
        player_is_blacklisted = true;
        player_region = player_region.replace('[blacklisted]', '');
      }
      
      // 解析地区ID和颜色
      if (player_region && player_region.includes('|')) {
        const parts = player_region.split('|');
        player_region = parts[0];
        player_region_id = parts[1];
        player_region_color = parts[2];
      }
      
      // 计算玩家总分
      // 1. 比赛得分
      const matchScoreTotal = player.scores.reduce((sum, score) => {
        const scoreValue = score.value;
        return sum + scoreValue;
      }, 0);
      
      // 2. 段位得分
      const tierScoreTotal = calculateTierScore(player);
      
      // 3. 总分 = 比赛分 + 段位分
      const totalScore = matchScoreTotal + tierScoreTotal;
      
      // 4. 计算等级称号
      const levelName = calculatePlayerLevel(totalScore);
      
      // 计算最高段位
      const tierValues = [
        player.swordTier,
        player.crystalTier,
        player.buhcTier,
        player.potionTier,
        player.npotTier,
        player.smpTier
      ].filter(value => value !== null && value !== undefined) as number[];
      
      const bestTierValue = tierValues.length > 0 ? Math.min(...tierValues) : null;
      const bestTierName = getTierName(bestTierValue);
      
      return {
        ...player,
        id: player.id.toString(),
        region: player_region,
        region_id: player_region_id,
        region_color: player_region_color,
        is_blacklisted: player_is_blacklisted,
        scores: player.scores.map(score => ({
          ...score,
          value: SCORE_MAP[score.mode as keyof typeof SCORE_MAP] || 0
        })),
        // 添加等级和分数信息
        score: totalScore,
        level_name: levelName,
        best_tier: bestTierValue,
        best_tier_name: bestTierName
      };
    });

    return NextResponse.json(formattedPlayers, {
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      }
    });
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to fetch players' },
      { status: 500 }
    );
  }
}

export async function POST(req: Request) {
  try {
    const { 
      name, 
      region, 
      avatar, 
      region_id, 
      region_color, 
      is_blacklisted 
    } = await req.json();
    
    if (!name || name.trim() === '') {
      return NextResponse.json(
        { error: '玩家名称不能为空' },
        { status: 400 }
      );
    }
    
    // 检查同名玩家是否已存在
    const existingPlayer = await prisma.player.findUnique({
      where: { name }
    });
    
    if (existingPlayer) {
      return NextResponse.json(
        { error: '该玩家名称已存在' },
        { status: 400 }
      );
    }
    
    // 存储地区信息
    let regionInfo = region || '未设置';
    // 如果有地区ID和颜色，将它们存储在regionInfo字段中
    if (region_id && region_color) {
      regionInfo = `${region}|${region_id}|${region_color}`;
    }
    
    // 黑名单信息也存储在region字段中（如果是黑名单，在region后添加[blacklisted]标记）
    if (is_blacklisted) {
      regionInfo = `${regionInfo}[blacklisted]`;
    }
    
    // 创建新玩家，只使用Prisma模型中确定存在的字段
    const playerData = {
      name,
      region: regionInfo,
      avatar: avatar || '/default-avatar.jpg',
      // 设置默认段位为null，表示"无等级"
      swordTier: null,
      crystalTier: null,
      buhcTier: null,
      potionTier: null,
      npotTier: null,
      smpTier: null
    };
    
    // 创建新玩家
    const newPlayer = await prisma.player.create({
      data: playerData
    });
    
    // 解析地区信息，重新添加到返回结果中
    let player_region = newPlayer.region;
    let player_region_id = null;
    let player_region_color = null;
    let player_is_blacklisted = false;
    
    // 检查是否为黑名单
    if (player_region.includes('[blacklisted]')) {
      player_is_blacklisted = true;
      player_region = player_region.replace('[blacklisted]', '');
    }
    
    // 解析地区ID和颜色
    if (player_region.includes('|')) {
      const parts = player_region.split('|');
      player_region = parts[0];
      player_region_id = parts[1];
      player_region_color = parts[2];
    }
    
    return NextResponse.json({
      success: true,
      player: {
        ...newPlayer,
        id: newPlayer.id.toString(),
        region: player_region,
        region_id: player_region_id,
        region_color: player_region_color,
        is_blacklisted: player_is_blacklisted
      }
    });
  } catch (error) {
    console.error('创建玩家失败:', error);
    return NextResponse.json(
      { error: 'Failed to create player' },
      { status: 500 }
    );
  }
}

export async function DELETE(req: Request) {
  try {
    const { id } = await req.json();
    await prisma.player.delete({
      where: { id: Number(id) }
    });
    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to delete player' },
      { status: 500 }
    );
  }
}
